package com.songyang.blog.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.songyang.blog.common.lang.Result;
import com.songyang.blog.entity.User;
import com.songyang.blog.entity.UserMessage;
import com.songyang.blog.util.CheckCodeUtil;
import com.songyang.blog.util.ValidationUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;

@Controller
public class AuthController extends BaseController {
    @GetMapping("/login")
    public String login() {
        return "/auth/login";
    }

    @ResponseBody
    @PostMapping("/login")
    public Result login(User user, String checkCode) {
        String getCheckCode = (String) request.getSession().getAttribute(CheckCodeUtil.getCheckCodeKey());
        if (user.getEmail() == null || user.getPassword() == null) {
            return Result.fail("账号邮箱或者密码不能为空!");
        }
        //加密的密码
        UsernamePasswordToken token = new UsernamePasswordToken(user.getEmail(), SecureUtil.md5(user.getPassword()));
        try {
            SecurityUtils.getSubject().login(token);
        } catch (AuthenticationException e) {
            if (e instanceof UnknownAccountException) {
                return Result.fail("用户不存在!我没有找到你的名字..");
            } else if (e instanceof LockedAccountException) {
                return Result.fail("用户被错定!");
            } else if (e instanceof IncorrectCredentialsException) {
                return Result.fail("密码错误!你的密码好像不太对呢！");
            } else
                return Result.fail("认证失败!");
        }
        return Result.success().action("/");
    }

    @GetMapping("/register")
    public String register() {
        return "/auth/reg";
    }

    @ResponseBody
    @PostMapping("/register")
    public Result toreg(User user, String repass, String checkCode) {
        String getCheckCode = (String) request.getSession().getAttribute(CheckCodeUtil.getCheckCodeKey());
        ValidationUtil.ValidResult validResult = ValidationUtil.validateBean(user);
        if (validResult.hasErrors()) {
            return Result.fail(validResult.getErrors());
        } else if (!user.getPassword().equals(repass)) {
            return Result.fail("两次密码输入不相同!");
        } else if (!getCheckCode.equalsIgnoreCase(checkCode)) {//不区分大小写验证
            return Result.fail("验证码输入不正确!");
        }
        Result result = userService.register(user);
        User userServiceOne = userService.getOne(new QueryWrapper<User>().eq("email", user.getEmail()));
        //注册成功就要发一条系统消息！
        UserMessage message = new UserMessage();
        message.setStatus(0);//未读状态
        message.setType(0);//系统消息
        message.setCreated(new Date());
        message.setToUserId(user.getId());
        String content=user.getUsername()+"您好!欢迎来到博客系统！";
        message.setContent(content);
        messageService.save(message);
        return result.action("/login");
    }

    @ResponseBody
    @GetMapping("/capthca.jpg")
    public void kaptcha(HttpServletResponse response) throws IOException {
        String text = producer.createText();//生成的验证码
        BufferedImage image = producer.createImage(text);
        response.setHeader("Cache-Control", "no-store");//告诉浏览器不要缓存这个
        response.setContentType("image/jpeg");//告诉浏览器这是个图片
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "jpg", outputStream);
    }

    @ResponseBody
    @GetMapping("/checkCode")
    public void checkCode(HttpServletResponse response, HttpServletRequest request) {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        CheckCodeUtil.getCheckCode(request, response);
    }

    @GetMapping("/user/logout")
    public String logout() {
        shiroUtils.logout();
        return "redirect:/";
    }
}
